package com.rokid.unitylibrary;

import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

import com.unity3d.player.UnityPlayer;
import com.unity3d.player.UnityPlayerActivity;

public class CustomUnityPlayerActivity extends UnityPlayerActivity {
    private CustomUnityPlayerActivity currentActivity;
    private static final String TAG = "CustomUnityPlayerActivity";

    // unity通信物体挂载的脚本
    private static final String mConnectorName = "UnityAndroidConnector";
    // unity接收android消息的方法
    private static final String mDefaultMethodName = "ReceiveAndroidMsg";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.i(TAG, "onCreate");
        currentActivity = this;
    }

    public void getString(String msg) {
        String a = "Unity:" + msg;
        Log.i(TAG, a);
        sendMsgToUnity(a);
    }

    public void sayToast(final String msg) {
        runOnUiThread(() -> Toast.makeText(currentActivity, msg, Toast.LENGTH_LONG).show());
    }
    /**
     * 发送消息给unity
     *
     * @param msg
     */
    public static void sendMsgToUnity(String msg) {
        UnityPlayer.UnitySendMessage(mConnectorName, mDefaultMethodName, msg);
    }

    /**
     * 发送消息给unity
     *
     * @param methodName
     * @param msg
     */
    public static void sendMsgToUnity(String methodName, String msg) {
        UnityPlayer.UnitySendMessage(mConnectorName, methodName, msg);
    }

    /**
     * 接收到Unity发来的消息
     *
     * @param key
     * @param msg
     */
    public void receiveUnityMsg(String key, String msg) {
        switch (key) {
            case "toast":
                sayToast(msg);
                break;
            case "getString":
                getString(msg);
                break;
        }
    }
}
